package com.example.layui_project.service.Impl;

import com.example.layui_project.comm.service.Impl.BaseServiceImpl;
import com.example.layui_project.dao.UserDao;
import com.example.layui_project.entity.SysUser;
import com.example.layui_project.service.UserService;
import com.example.layui_project.utils.BestUitls;
import com.example.layui_project.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends BaseServiceImpl<SysUser> implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public boolean isExist(SysUser user) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("username",user.getUserName()).andEqualTo("password", MD5Util.md5to32string(user.getPassword()));
        SysUser sysUser = userDao.selectOneByExample(example);
        return BestUitls.isNotBlank(sysUser) ? true : false;
    }

    @Override
    public SysUser isExist(String username) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("username",username);
        SysUser sysUser = userDao.selectOneByExample(example);
        return BestUitls.isNotBlank(sysUser) ? sysUser : null;
    }

    @Override
    @Transactional
    public boolean add(SysUser user) {
        user.setPassword(MD5Util.md5to32string("123456"));
        user.setCreateTime(new Date());
        int i = userDao.insertUseGeneratedKeys(user);
        if(i>0){
            int rowNum = userDao.batchAdd(user.getRoles(), user);
            return rowNum > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean del(Integer id) {
        int i = userDao.deleteByPrimaryKey(id);
        return i>0 ? true : false;
    }

    @Override
    @Transactional
    public boolean update(SysUser user) {
        int i = userDao.updateByPrimaryKeySelective(user);
        if(i>0){
            int delRow = userDao.removeAllUserRole(user.getId());
            if (delRow>=0){
                int rowNum = userDao.batchAdd(user.getRoles(), user);
                return rowNum > 0 ? true : false;
            }
        }
        return false;
    }

    @Override
    public SysUser getAllRoleAndPermissionByUser(String username) {
        return userDao.getAllRoleAndPermissionByUser(username);
    }
}
